package top.infopub.security.listener;


import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import top.infopub.security.service.SysPurviewService;
import top.infopub.security.vo.PurviewVO;
import top.infopub.util.SpringContext;
import top.infopub.zookeeper.confclient.ContextUtils;
import top.infopub.zookeeper.confclient.listener.ConfigurationListener;


/**
 * ShiroChainUpdate
 * @author Awoke
 * @version 2018年9月17日
 * @see ShiroChainUpdate
 * @since
 */
public class ShiroChainUpdate implements ConfigurationListener {

    private static final Logger log = LoggerFactory.getLogger(ShiroChainUpdate.class);

    private ShiroFilterFactoryBean shiroFilterFactoryBean;

    private String filterChainDefinitions;

    private boolean alluserLogin = false;

    /**
     * 默认premission字符串
     */
    public static final String PREMISSION_STRING = "perms[\"{0}\"]";

    public synchronized void updatePermission() {
        shiroFilterFactoryBean = SpringContext.getBean(ShiroFilterFactoryBean.class);
        AbstractShiroFilter shiroFilter = null;
        try {
            shiroFilter = (AbstractShiroFilter)shiroFilterFactoryBean.getObject();

            // 获取过滤管理器
            PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver)shiroFilter.getFilterChainResolver();
            DefaultFilterChainManager manager = (DefaultFilterChainManager)filterChainResolver.getFilterChainManager();

            // 清空初始权限配置
            manager.getFilterChains().clear();
            shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();

            // 重新构建生成
            shiroFilterFactoryBean.setFilterChainDefinitions(filterChainDefinitions);
            Map<String, String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();

            for (Map.Entry<String, String> entry : chains.entrySet()) {
                String url = entry.getKey();
                String chainDefinition = entry.getValue().trim().replace(" ", "");
                manager.createChain(url, chainDefinition);
            }
            Map<String, List<String>> purviews = new HashMap<String, List<String>>();

            List<PurviewVO> _PurviewVOList = new ArrayList<PurviewVO>();
            _PurviewVOList = SpringContext.getBean(SysPurviewService.class).queryAll();
            for (PurviewVO pur : _PurviewVOList) {
                String purviewurl = pur.getPurviewUrl();
                if (purviewurl.contains(";")) {
                    String[] temp = pur.getPurviewUrl().split(";");
                    for (int i = 0; i < temp.length; i++ ) {
                        if (StringUtils.isNotEmpty(temp[i])
                            && StringUtils.isNotEmpty(pur.getPurviewCode())) {
                            if (purviews.containsKey(temp[i])) {
                                purviews.get(temp[i]).add(pur.getPurviewCode());
                            }
                            else {
                                List<String> purCodes = new ArrayList<String>();
                                purCodes.add(pur.getPurviewCode());
                                purviews.put(temp[i], purCodes);
                            }
                        }
                    }
                }
                else {
                    if (purviews.containsKey(purviewurl)) {
                        purviews.get(purviewurl).add(pur.getPurviewCode());
                    }
                    else {
                        List<String> purCodes = new ArrayList<String>();
                        purCodes.add(pur.getPurviewCode());
                        purviews.put(purviewurl, purCodes);
                    }
                }
            }
            for (String key : purviews.keySet()) {
                manager.createChain(
                    key,
                    "user,concurrentlogin,"
                        + MessageFormat.format(PREMISSION_STRING,
                            StringUtils.join(purviews.get(key), ',')));
            }
            if (alluserLogin) {
                manager.createChain("/**", "user,concurrentlogin");
            }
        }
        catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        log.info(ContextUtils.PROJECT_NAME + " 更新权限成功");
    }

    /**
     * 默认的url过滤定义
     */
    public void setFilterChainDefinitions(String filterChainDefinitions) {
        this.filterChainDefinitions = filterChainDefinitions;
    }

    @Override
    public void configurationChangedNotice(String keyName, String data) {
        // 收到ChangedNotice后 更新权限数据 
        this.updatePermission();
    }

    public boolean isAlluserLogin() {
        return alluserLogin;
    }

    public void setAlluserLogin(boolean alluserLogin) {
        this.alluserLogin = alluserLogin;
    }

}